"""配置管理模块"""
import os
import json
import platform
import pathlib
from typing import Dict, Optional

# 配置文件路径（用户主目录下的隐藏文件）
config_dir = pathlib.Path.home() / ".config" / "ytcc"
config_dir.mkdir(parents=True, exist_ok=True)
CONFIG_FILE_PATH = os.path.expanduser("~/.config/ytcc/config.json")


def load_config() -> Dict[str, str]:
    """从配置文件加载保存的API密钥和代理设置"""
    config = {}
    if os.path.exists(CONFIG_FILE_PATH):
        try:
            with open(CONFIG_FILE_PATH, "r", encoding="utf-8") as f:
                config = json.load(f)
        except json.JSONDecodeError:
            print(f"警告：配置文件 {CONFIG_FILE_PATH} 格式错误，将忽略")
        except Exception as e:
            print(f"警告：读取配置文件失败: {str(e)}，将忽略")
    
    # 返回有效配置，过滤空值
    return {
        key: value.strip() 
        for key, value in config.items() 
        if key in ["api_key", "proxy"] and value and value.strip()
    }


def save_config(api_key: str, proxy: Optional[str]) -> None:
    """将API密钥和代理设置保存到配置文件"""
    try:
        config = {"api_key": api_key.strip()}
        if proxy and proxy.strip():
            config["proxy"] = proxy.strip()
            
        with open(CONFIG_FILE_PATH, "w", encoding="utf-8") as f:
            json.dump(config, f, ensure_ascii=False, indent=2)
        
        # 在类Unix系统上设置文件权限，确保只有当前用户可读写
        if platform.system() in ("Linux", "Darwin"):
            os.chmod(CONFIG_FILE_PATH, 0o600)
            
        print(f"配置已保存到 {CONFIG_FILE_PATH}，下次运行无需指定API密钥和代理")
    except Exception as e:
        print(f"警告：保存配置文件失败: {str(e)}")


def print_api_key_setup_instructions() -> None:
    """打印API密钥配置指南"""
    print("未检测到有效的YouTube Data API密钥，请按以下步骤配置：")
    print("\n1. 获取API密钥：")
    print("   - 登录Google Cloud控制台")
    print("     https://console.cloud.google.com/")
    print("   - 启用YouTube Data API v3")
    print("     https://console.cloud.google.com/marketplace/product/google/youtube.googleapis.com")
    print("   - 创建API密钥并复制")
    print("     https://console.cloud.google.com/apis/credentials")
    
    print("2. 直接在命令行中指定（首次设置会自动保存）：")
    print("   ytcc 视频ID --api-key 你的API密钥 [--proxy 代理地址]\n")
    